<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增模块类型 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:eye-outlined',
                label: '查看属性',
                onClick: handleViewAttrs.bind(null, record),
              },
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <ModuleTypeModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getModuleTypeList, deleteModuleType } from '@/api/module/module';
  import { columns, searchFormSchema } from './moduleType.data';
  import { useModal } from '@/components/Modal';
  import ModuleTypeModal from './ModuleTypeModal.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';

  const { createMessage } = useMessage();
  const router = useRouter();
  const [registerModal, { openModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    title: '模块类型列表',
    api: getModuleTypeList,
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      key: 'action',
    },
  });

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete(record: Recordable) {
    try {
      await deleteModuleType({ id: record.id });
      createMessage.success('删除成功');
      reload();
    } catch (err) {
      console.error('删除失败:', err);
    }
  }

  async function handleViewAttrs(record: Recordable) {
    router.push({
      path: '/template/module-attr',
      query: {
        name: record.name,
        size: 200,
      },
    });
  }

  function handleSuccess() {
    reload();
  }
</script>
